using System;
using System.IO;
using System.Text;
using Comdiv.Extensions;
using Comdiv.Model;
using Comdiv.Model.Interfaces;
using Comdiv.Logging;
using Comdiv.Application;
using Comdiv.Persistence;
using Comdiv.Inversion;
using Comdiv.Security.Acl;
using Comdiv.Conversations;
using Comdiv.IO;
using Comdiv.Security;
using System.Linq;


namespace wikiviewer.Controllers{
    public class WikiTableFormatter : IWikiFormatter
    {
        public int Idx { get; set; }


        private bool isintable;
        private StringBuilder builder;
        

        public string Process(string current)
        {
            builder = new StringBuilder();
            var stringreader = new StringReader(current);
            string line = "";
            while (null != (line = stringreader.ReadLine()))
            {
                var state = gettable(line);
                if (state.istable)
                {
                    if(!isintable){
                        isintable = true;
                        builder.Append("<table>");
                    }
                    builder.Append("<tr>");
                    foreach (var cell in state.cells){
                        builder.Append("<td>");
                        builder.Append(cell);
                        builder.Append("</td>");
                    }
                    builder.Append("</tr>");
                }
                else
                {
                    if (isintable)
                    {
                        isintable = false;
                        builder.Append("</table>");
                    }
                    builder.AppendLine(line);
                }
            }
            return builder.ToString();
        }

        private TableState gettable(string line){
            var result = new TableState();
            if(line.StartsWith("||")){
                result.istable = true;
                result.cells = line.Split(new[] { "||" }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray();
            }
            return result;
        }

        private class TableState{
            public bool istable;
            public string[] cells;
        }
    }
}